package com.youlu.campus.admin.feedback.service.impl;

import com.alibaba.fastjson.JSON;
import com.mongodb.client.result.UpdateResult;
import com.youlu.campus.admin.auth.service.UserService;
import com.youlu.campus.admin.base.BaseService;
import com.youlu.campus.admin.feedback.dto.FeedBackQueryRequest;
import com.youlu.campus.admin.feedback.dto.FeedBackQueryResponse;
import com.youlu.campus.admin.feedback.entity.FeedBackInfo;
import com.youlu.campus.admin.feedback.service.FeedBackInfoService;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.component.SmsUtil;
import com.youlu.campus.entity.*;
import com.youlu.campus.service.sms.SmsTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
@Slf4j
public class FeedBackInfoServiceImpl extends BaseService implements FeedBackInfoService {
    @Autowired
    private SmsTemplateService smsTemplateService;
    @Autowired
    private SmsUtil smsUtil;
    @Autowired
    private UserService userService;

    @Override
    public Page<FeedBackQueryResponse> list(FeedBackQueryRequest requst) {
        log.info(":>>> 开始查询问题反馈:{}", requst);
        if (Objects.isNull(requst)) {
            log.error(":>>> 查询问题反馈参数错误");
            throw new BusinessException("参数错误!");
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("deleted").ne(Boolean.TRUE));
        if (Objects.nonNull(requst.getStatus())) {
            query.addCriteria(Criteria.where("status").is(requst.getStatus()));
        }
        if (StringUtils.isNotBlank(requst.getMobile())) {
            Pattern pattern = Pattern.compile("^.*" + requst.getMobile() + ".*$", Pattern.CASE_INSENSITIVE);
            query.addCriteria(Criteria.where("mobile").regex(pattern));
        }
        if (StringUtils.isNotBlank(requst.getContent())) {
            Pattern pattern = Pattern.compile("^.*" + requst.getContent() + ".*$", Pattern.CASE_INSENSITIVE);
            query.addCriteria(Criteria.where("content").regex(pattern));
        }
        if (StringUtils.isNotBlank(requst.getQq())) {
            Pattern pattern = Pattern.compile("^.*" + requst.getQq() + ".*$", Pattern.CASE_INSENSITIVE);
            query.addCriteria(Criteria.where("qq").regex(pattern));
        }
        if (StringUtils.isNotBlank(requst.getName())) {
            Pattern pattern = Pattern.compile("^.*" + requst.getName() + ".*$", Pattern.CASE_INSENSITIVE);
            query.addCriteria(Criteria.where("name").regex(pattern));
        }
        if (StringUtils.isNotBlank(requst.getUniversityId())) {
            Pattern pattern = Pattern.compile("^.*" + requst.getUniversityId() + ".*$", Pattern.CASE_INSENSITIVE);
            query.addCriteria(Criteria.where("university").regex(pattern));
        }
        long count = mongoTemplate.count(query, FeedBackInfo.class);
        PageRequest pageRequest = PageRequest.of(requst.getPage() - 1, requst.getPageSize());
//        query.with(new Sort(Sort.Direction.DESC, "createdTime"));
        Sort sort=Sort.by(Sort.Direction.DESC, "createdTime");
        query.with(sort);
        List<FeedBackInfo> datas = mongoTemplate.find(query.with(pageRequest), FeedBackInfo.class);
        List<FeedBackQueryResponse> list = datas.stream().map(data -> {
            FeedBackQueryResponse response = mapperFacade.map(data, FeedBackQueryResponse.class);
            response.setUserNickName(data.getName());
            if (StringUtils.isBlank(response.getMobile())) {
                /**
                 * 状态,0:待付款,1:已付款,2:制作中,3:待发货,4:待收货,5:已收货,6:订单完成,7:订单关闭,8:售后中,9:部分已发货
                 */
                List<String> statuses = new ArrayList<>();
                statuses.add("1");
                statuses.add("4");
                statuses.add("9");
                statuses.add("6");
                Query queryOrder = new Query().addCriteria(Criteria.where("accountInfoId").is(data.getUserId()).and("status").in(statuses));
                OrderInfo orderInfo = mongoTemplate.findOne(queryOrder, OrderInfo.class);
                if (Objects.nonNull(orderInfo)) {
                    response.setUserNickName(orderInfo.getName());
                    if (StringUtils.isNotBlank(orderInfo.getMobile())) {
                        response.setMobile(orderInfo.getMobile());
                    } else {
                        Query queryUserPo = new Query().addCriteria(Criteria.where("userId").is(data.getUserId()).and("joined").is(Boolean.TRUE));
                        UserParticipateActivityInfo userPO = mongoTemplate.findOne(queryUserPo, UserParticipateActivityInfo.class);
                        if (Objects.nonNull(userPO)) {
                            response.setMobile(userPO.getMobile());
                            response.setUserNickName(userPO.getName());
                        }
                    }
                }
            }

            return response;
        }).collect(Collectors.toList());
        return PageableExecutionUtils.getPage(list, pageRequest, () -> count);
    }

    @Override
    public boolean updateFeedBackInfo(FeedBackInfo info) {
        log.info(":>>> 开始修改用户反馈:{}", JSON.toJSONString(info));
        if (Objects.isNull(info) || StringUtils.isBlank(info.getId()) || Objects.isNull(info.getStatus())) {
            log.error(":>>> 修改问题反馈参数错误");
            throw new BusinessException("参数错误!");
        }
        Query query = new Query().addCriteria(Criteria.where("id").is(info.getId()));
        FeedBackInfo exist = mongoTemplate.findOne(query, FeedBackInfo.class);
        if (Objects.isNull(exist)) {
            log.error(":>>> 数据不存在");
            throw new BusinessException("数据不存在!");
        }
        Date date = new Date();
        Update update = new Update();
        update.set("status", info.getStatus());
        update.set("updatedTime", date);
        if (StringUtils.isNotBlank(info.getComment())) {
            update.set("comment", info.getComment());
        }
        if (StringUtils.isNotBlank(info.getHanleUser())) {
            update.set("handleUser", info.getHanleUser());
            update.set("hanleTime", date);
        }
        boolean updateResult = mongoTemplate.updateFirst(query, update, FeedBackInfo.class).getModifiedCount() > 0 ? true : false;
        log.info(":>>> 处理反馈结果:{} 用户手机号;{},提交信息:{}", updateResult, exist.getMobile(), info.getComment());
        if (Boolean.TRUE.equals(info.getSendSms()) && updateResult && StringUtils.isNotBlank(exist.getMobile()) && StringUtils.isNotBlank(info.getComment())) {
            String[] params = new String[1];
            params[0] = info.getComment();
            sendFeedBackMsg(exist.getMobile(), params);
        }
        return updateResult;
    }

    @Override
    public boolean delete(String id) {
        Query query=new Query();
        query.addCriteria(Criteria.where("id").is(id));
        Update update=new Update();
        update.set("deleted",true);
        update.set("updatedTime",new Date());
        return mongoTemplate.updateFirst(query,update,FeedBackInfo.class).getModifiedCount()>0?true:false;
    }

    private void sendFeedBackMsg(String mobile, String[] params) {

        SmsTemplate smsTemplate = smsTemplateService.findBySmsTemplate("", "梦想跳动", "feed-back");
        if (Objects.isNull(smsTemplate) || StringUtils.isBlank(smsTemplate.getSign()) || Objects.isNull(smsTemplate.getTempalteId())) {
            log.error(":>>> 短信模版配置错误:没有配置");
            return;
//            throw new BusinessException("短信模版配置错误");
        }
        smsUtil.sendSmsWithContent("梦想跳动", mobile, smsTemplate.getTempalteId(), params);

    }
}
